const cartModule = {
  state: {
    cart: [],
  },
  getters: {
    // 计算获取购物车中商品的总数量
    totalCarts(state) {
      return state.cart.reduce((sum, item) => sum + item.amount, 0)
    },
    // 计算选中商品的合计金额
    totalCartsPrice(state) {
      return state.cart.reduce((sum, item) => {
        if (item.checked) {
          sum += item.amount * item.price
        }
        return sum
      }, 0) * 100
    },
    // 计算是否所有商品全选
    changeAllChecked(state) {
      return state.cart.every(item => item.checked)
    },
  },
  mutations: {
    // 添加商品
    addCart(state, payload) {
      const flag = state.cart.some(item => payload.id === item.id)
      if (flag) {
        state.cart = state.cart.map(item => {
          const copy = { ...item }
          if (copy.id === payload.id) {
            copy.amount += payload.amount
          }
          return copy
        })
      } else {
        const copy = {
          ...payload,
          checked: true,
        }
        state.cart.push(copy)
      }
    },
    // 数量加减
    updataCart(state, payload) {
      state.cart = state.cart.map(item => {
        const copy = { ...item }
        if (copy.id === payload.id) {
          copy.amount = payload.amount
        }
        return copy
      })
    },
    // 删除商品
    deleteCart(state, payload) {
      state.cart = state.cart.filter(item => item.id !== payload.id)
    },
    // 修改商品的选中状态
    changeChecked(state, payload) {
      state.cart = state.cart.map(item => {
        const copy = { ...item }
        if (copy.id === payload.id) {
          copy.checked = !copy.checked
        }
        return copy
      })
    },
    // 全选/取消全选
    checkAll(state, payload) {
      state.cart = state.cart.map(item => {
        const copy = { ...item }
        copy.checked = payload.checked
        return copy
      })
    },
  },
  actions: {},
  module: {},
}
export default cartModule
